﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Ionic.Zip;
using ManagedServices.UI.Web.Models;

namespace ManagedServices.UI.Web.Controllers
{
    public class AddSubServiceController : Controller
    {
        //
        // GET: /AddSubService/
        [HttpPost]
        public ActionResult UploadSubService()
        {
            string zipFileName = string.Empty;
            foreach (string file in Request.Files)
            {
                HttpPostedFileBase hpf = Request.Files[file];
                if (hpf.ContentLength == 0)
                    continue;
                zipFileName = Path.Combine(Utility.GetInstallDirectory(),
                   Path.GetFileName(hpf.FileName));
                hpf.SaveAs(zipFileName);
            }

            string extractLocation = Path.Combine(Utility.GetInstallDirectory(), Utility.NewSubServiceDirectory); 
            using (ZipFile zip1 = ZipFile.Read(zipFileName))
            {
                // here, we extract every entry, but we could extract conditionally
                // based on entry name, size, date, checkbox status, etc.  
                foreach (ZipEntry e in zip1)
                {
                    e.Extract(extractLocation, ExtractExistingFileAction.OverwriteSilently);
                }
            }

            List<UploadedFileModel> uploadedFiles = new List<UploadedFileModel>();
            foreach (var item in Directory.GetFiles(extractLocation))
            {
                FileInfo fi = new FileInfo(item);
                
                string filetype = "Unknown";
                if(fi.Extension.ToLower() == ".dll")
                {
                    filetype = "Assembly";
                }
                else if (fi.Extension.ToLower() == ".config")
                {
                    filetype = "Configuration";
                }
                else if (fi.Extension.ToLower() == ".settings")
                {
                    filetype = "Dynamic Settings File";
                }
                else if (fi.Extension.ToLower() == ".meta")
                {
                    filetype = "Sub Service Metadata file";
                }
                uploadedFiles.Add(new UploadedFileModel { FileName = fi.Name, FileType=filetype });
            }

            ViewData["Message"] = "File Successfully Uploaded !";
            return View(uploadedFiles);
        }

        
        public ActionResult ReviewUpload()
        {
            string extractLocation = Path.Combine(Utility.GetInstallDirectory(), Utility.NewSubServiceDirectory);
            string metafileName = string.Empty;
            foreach (var item in Directory.GetFiles(extractLocation))
            {
                if (item.ToLower().Contains("meta"))
                {
                    metafileName = item;
                    break;
                }
            }
            string allMetaContents = System.IO.File.ReadAllText(metafileName);
            var modelInst = Utility.XmlDeSerialize<SubServiceMetadataModel>(allMetaContents);
            return View(modelInst);

        }

        public ActionResult ConfirmUpload()
        {
            string extractLocation = Path.Combine(Utility.GetInstallDirectory(), Utility.NewSubServiceDirectory);
            string metafileName = string.Empty;
            foreach (var item in Directory.GetFiles(extractLocation))
            {
                if (item.ToLower().Contains("meta"))
                {
                    metafileName = item;
                    break;
                }
            }
            string allMetaContents = System.IO.File.ReadAllText(metafileName);
            var modelInst = Utility.XmlDeSerialize<SubServiceMetadataModel>(allMetaContents);
            DTOConverter.PersistSubServiceMetadataModel(modelInst, GetBinaryFile);
            ViewData["Message"] = "All details successfully uploaded!";
            return View(modelInst);
        }

        private static System.Data.Linq.Binary GetBinaryFile(string file)
        {
            string extractLocation = Path.Combine(Utility.GetInstallDirectory(), Utility.NewSubServiceDirectory);
            string fileName = string.Empty;
            foreach (var item in Directory.GetFiles(extractLocation))
            {
                if (item.ToLower().Contains(fileName))
                {
                    fileName = item;
                    break;
                }
            }
            return System.IO.File.ReadAllBytes(fileName);
        }
    }
}
